package com.dk.smsexpress;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.rpc.server.JsonRpcExecutor;
import org.json.rpc.server.JsonRpcServletTransport;

import com.dk.smsexpress.common.ServiceConstant;
import com.dk.smsexpress.common.base.IMobiSmsAutoSelectAccount;
import com.dk.smsexpress.common.base.IMobiSmsManualSelectAccount;
import com.dk.smsexpress.common.base.MobiAccount;
import com.dk.smsexpress.common.exception.SmsException;
import com.dk.smsexpress.server.imp.MobiSms;
import com.dk.smsexpress.server.imp.MobiSmsAutoSelectAccount;
import com.dk.smsexpress.server.imp.MobiSmsManualSelectAccount;

@SuppressWarnings("serial")
public class SmsExpress_serverServlet extends HttpServlet {
	private JsonRpcExecutor executor;

	@Override
	public void init() throws ServletException {
		super.init();
		executor = bind();

	}

	@SuppressWarnings("unchecked")
	private JsonRpcExecutor bind() {
		JsonRpcExecutor executor = new JsonRpcExecutor();

		IMobiSmsManualSelectAccount mobiSmsManual = new MobiSmsManualSelectAccount();
		executor.addHandler(ServiceConstant.MOBIFONE_SMS_MANUAL, mobiSmsManual,
				IMobiSmsManualSelectAccount.class);

		IMobiSmsAutoSelectAccount mobiSmsAuto = new MobiSmsAutoSelectAccount();
		executor.addHandler(ServiceConstant.MOBIFONE_SMS_AUTO, mobiSmsAuto,
				IMobiSmsAutoSelectAccount.class);

		// add more services here
		return executor;
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");
		resp.getWriter().println("L.Le 25-Jul-2011");
		if (req.getParameter("username") != null) {
			long startTime = System.currentTimeMillis();			
			MobiAccount account = new MobiAccount("0933477833", "FirstDoc123");
			try {
				MobiSms mobiSms = new MobiSms(account);
				mobiSms.setPhoneNum("84933477833");
				mobiSms.setMessage("L.Le 26-Jul-2011 Sample Text");
				if (mobiSms.getMessageLeft() > 0) {
					mobiSms.sendMessage();
				}
				
			} catch (SmsException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			long endTime = System.currentTimeMillis();
			
			resp.getWriter().println("Execusion Time:"+(endTime-startTime)/100);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		executor.execute(new JsonRpcServletTransport(request, response));		
	}
}
